<?php

namespace App\Http\Controllers;

use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class MessageController extends Controller
{
    public $nav = [];

    public function __construct()
    {
        $this->nav = Nav::orderBy('order', 'asc')->get()->toArray();
    }

    public function index()
    {
        return view('http.message',['nav'=>$this->nav]);
    }

    public function add(Request $request)
    {
        $this->validate($request,[
            'title' => 'required',
            'content' => 'required'
        ]);

        $message = new Message();
        $message->title = $request->post('title');
        $message->content = $request->post('content');
        $flag = $message->save();

        if ($flag) {

            $title = $message->title;
            $content = $message->content;

            $to = 'zhenzihan1110@163.com';

            //纯文本
            /*Mail::raw($content, function($msg) use ($to, $title) {
                $msg->to($to)->subject($title);
            });*/

            //发送纯文本内容 + 附件
            /*Mail::raw($content, function($msg) use ($to, $title) {
                $msg->to($to)->subject($title);

                $attachment = public_path().'/storage/seller/1.png';
                if (!file_exists($attachment)) {
                    die('文件不存在');
                }
                // 防止中文乱码
                $msg->attach($attachment, ['as' => '=?UTF-8?B?'.base64_encode('二维码图片').'?=.png']);
            });*/

            //发送模板内容 + 附件
            Mail::send('http.template', compact('content'), function($msg) use ($to, $title) {
                $msg->to($to)->subject($title);
                /*$attachment = public_path().'/storage/seller/1.png';
                if (!file_exists($attachment)) {
                    die('文件不存在');
                }
                // 防止中文乱码
                $msg->attach($attachment, ['as' => '=?UTF-8?B?'.base64_encode('二维码图片').'?=.png']);*/
            });

            return response()->json([
                'status_code' => 1,
                'message'     => '成功',
            ]);
        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '失败',
            ]);
        }
    }
}